<template>
  <!-- 顶部导航栏 -->
  <div>
    <van-nav-bar title="首页" left-text="" left-arrow @click-left="onClickLeft" />
  </div>

  <!-- 搜索表单 -->
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <div class="search-div">
        <van-field
            v-model="stationName"
            name="目的地"
            left-icon="search"
            placeholder="搜索目的地/充电站"
            :rules="[{ required: true, message: '' }]"
        />
      </div>
    </van-cell-group>
  </van-form>

  <!-- 分类标签页 -->
  <van-tabs v-model:active="active">
    <van-tab title="距离最近"></van-tab>
    <van-tab title="价格最低"></van-tab>
    <van-tab title="评价最好"></van-tab>
    <van-tab title="人气最高"></van-tab>
  </van-tabs>

  <div class="custom-line"></div>

  <!-- 筛选按钮区域 -->
  <div class="button-div">
    <div style="margin-right: 5px;">
      <van-button
          type="default"
          size="small"
          :class="{ 'is-blue': isBlue }"
          @click="toggleFilter('washFee')"
      >免费停车</van-button>
    </div>
    <div style="margin-right: 5px;">
      <van-button
          type="default"
          size="small"
          :class="{ 'is-blue': isBlue1 }"
          @click="toggleFilter('shoppingMall')"
      >大型商场</van-button>
    </div>
    <div style="margin-right: 5px;">
      <van-button
          type="default"
          size="small"
          :class="{ 'is-blue': isBlue2 }"
          @click="toggleFilter('lounge')"
      >休息室</van-button>
    </div>
    <div style="margin-right: 5px;">
      <van-button
          type="default"
          size="small"
          :class="{ 'is-blue': isBlue3 }"
          @click="toggleFilter('restroom')"
      >卫生间</van-button>
    </div>
    <div style="margin-right: 5px;">
      <van-button
          type="default"
          size="small"
          :class="{ 'is-blue': isBlue4 }"
          @click="toggleFilter('carWash')"
      >洗车服务</van-button>
    </div>
  </div>

  <!-- 充电站列表展示区域 -->
  <div style="background-color: whitesmoke; padding: 16px;">
    <div v-for="(item, index) in stationInfo" :key="index" style="background-color: white; margin-bottom: 5px; height: 100px;" @click="StationDetailPage(item.id)">
      <!-- 站点基本信息 -->
      <van-space :align="align">
        <div style="height: 48px; width: 200px;">
          <h4 style="margin-top: 3px; margin-bottom: 3px">{{ item.stationName }}</h4>
          <div style="display: flex;">
            <img style="height: 20px;" alt="Vue logo" src="../../images/24hours.png" />
            <div style="margin-left: 3px;">{{ item.businessStartTime }} | </div>
          </div>
        </div>
        <div style="height: 48px; width: auto; background-color: white; padding-top: 5px;">
          <div style="color: blue; font-weight: bolder; font-size: 18px;">{{ item.price }}/度</div>
        </div>
      </van-space>

      <!-- 充电桩数量信息 -->
      <div style="display: flex; height: 20px;">
        <div style="background-color: red;">空：{{ item.availableCount }}</div>
        <div style="background-color: cyan;">共：{{ item.totalCount }}</div>
      </div>

      <!-- 站点地址和距离信息 -->
      <div class="station-footer" style="display: flex; margin-bottom: 5px; padding-top: 10px;">
        <img style="height: 20px;" src="../../images/map.png" />
        <div style="margin-left: 3px; font-size: 12px;">{{ item.address }}</div>
        <div style="display: flex; margin-left: auto; margin-right: 0%;">
          <div style="text-align: right;">{{ item.latitude }}Km</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import router from '@/router';
import { ref, watch } from 'vue';
import { GetStationList } from '@/api/station';
import { GetUserInfo } from '@/api/user';

const stationName = ref('');
const active = ref(0);  // 当前选择的标签
const align = ref('center');
const stationInfo = ref([]);
const userId = ref(null); // 当前登录用户的 ID
const isBlue = ref(false);
const isBlue1 = ref(false);
const isBlue2 = ref(false);
const isBlue3 = ref(false);
const isBlue4 = ref(false);

// 过滤条件
const filter = ref({
  washFee: 0,        // 免费停车
  shoppingMall: 0,   // 大型商场
  lounge: 0,         // 休息室
  restroom: 0,       // 卫生间
  carWash: 0,        // 洗车服务
});
resetFilters()

// 获取用户信息
function getUserInfo() {
  GetUserInfo().then((res) => {
    if (res.data.code === 200000) {
      userId.value = res.data.data.id;
      console.log("登录用户 ID:", userId.value);
      getStationInfo();
    } else {
      console.error('获取用户信息失败:', res.data.message);
    }
  }).catch((err) => {
    console.error("获取用户信息出错:", err);
  });
}

// 获取站点信息并传递筛选条件
function getStationInfo() {
  if (!userId.value) {
    console.error('用户 ID 未获取');
    return;
  }

  GetStationList({
    userId: String(userId.value),
    ...filter.value, // 动态传递筛选条件
    stationName: stationName.value,
  }).then((res) => {
    if (res.data.code === 200000) {
      stationInfo.value = res.data.data;
      sortStationInfo();  // 获取到数据后进行排序
    } else {
      console.error('获取站点列表失败:', res.data.message);
    }
  }).catch((err) => {
    console.error('获取站点列表出错:', err);
  });
}

// 按照价格或距离排序
function sortStationInfo() {
  if (active.value === 1) {  // "价格最低"选项
    stationInfo.value.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));
  } else if (active.value === 0) { // "距离最近"选项
    stationInfo.value.sort((a, b) => parseFloat(a.latitude) - parseFloat(b.latitude));
  }
}

// 提交表单
function onSubmit() {
  console.info('提交');
}

// 点击站点跳转到详情页面
function StationDetailPage(id) {
  router.push({
    path: '/station/detail',
    query: { id: id }
  });
}

// 切换筛选按钮状态
function toggleFilter(type) {
  if (type === 'washFee') {
    isBlue.value =!isBlue.value;
    filter.value.washFee = isBlue.value? 1 : null; // 使用 null 表示不选择
  } else if (type === 'shoppingMall') {
    isBlue1.value =!isBlue1.value;
    filter.value.shoppingMall = isBlue1.value? 1 : null;
  } else if (type === 'lounge') {
    isBlue2.value =!isBlue2.value;
    filter.value.lounge = isBlue2.value? 1 : null;
  } else if (type === 'restroom') {
    isBlue3.value =!isBlue3.value;
    filter.value.restroom = isBlue3.value? 1 : null;
  } else if (type === 'carWash') {
    isBlue4.value =!isBlue4.value;
    filter.value.carWash = isBlue4.value? 1 : null;
  }

  // 更新筛选条件并重新获取站点信息
  getStationInfo();
}

// 重置筛选条件
function resetFilters() {
  // 重置所有筛选按钮状态
  isBlue.value = false;
  isBlue1.value = false;
  isBlue2.value = false;
  isBlue3.value = false;
  isBlue4.value = false;

  // 清空筛选条件
  filter.value = {
    washFee: null,
    shoppingMall: null,
    lounge: null,
    restroom: null,
    carWash: null,
  };

  // 获取所有充电站信息
  getStationInfo();
}

// 监听 active 变化，当选择"价格最低"时进行排序
watch(active, (newVal) => {
  sortStationInfo();  // 根据选项变化进行排序
});

// 初始调用获取用户信息
getUserInfo();
</script>



<style>
.search-div {
  display: flex;
}

.button-div {
  margin-top: 10px;
  margin-left: 16px;
  display: flex;
}

.is-blue {
  background-color: lightskyblue; /* 蓝色背景 */
}

.custom-line {
  margin-top: 3px;
  border-bottom: 0.5px solid lightgray; /* 灰色细线 */
  width: 100%;
}

.station-footer {
  display: flex;
  justify-content: space-between;
}

.strike-line {
  font-weight: bold;
  margin-left: 5px;
}
</style>